
import Axios from 'axios'
import { Message, Loading } from 'element-ui'
import { CommonModule } from '@/store/modules/common'
let baseUrl: any = process.env.VUE_APP_BASE_API
if (process.env.VUE_APP_ENTRY !== 'main') {
  baseUrl = 'https://test4-v7.7moor.com/'
}
const service = Axios.create({
  baseURL: baseUrl,
  responseType: 'json',
  timeout: 30000
})
const ignoreName = [ // 后端返回success: false的时候，如不想提示message,可把接口名加入到此数组中，切记要备注好每个接口名的意思
  '/im-center/action/webchat/replyMsg', // 在线发送消息接口
  '/call/action/biz/dialOut' // 外呼接口
]
// cout不为0有遮照
let count = 0
let loadingInstance: any = null
service.interceptors.request.use((res) => {
  // @ts-ignore: Unreachable code error
  if (res.hideLoading) { // 取消loading
    count = 0
    loadingInstance.close()
  } else { // 需要loading
    count++
    loadingInstance = Loading.service({ background: 'rgba(0,0,0,0)', spinner: 'a' })
  }
  // @ts-ignore: Unreachable code error
  const sessionId = CommonModule.session._id || ''
  // @ts-ignore: Unreachable code error
  const loginToken = CommonModule.session.user && CommonModule.session.user.loginToken ? CommonModule.session.user.loginToken : ''
  let lang = window.localStorage.getItem('lang')
  if (!lang) {
    lang = 'zh_CN'
  }
  if (sessionId && loginToken) {
    res.headers.sessionId = sessionId
    res.headers.loginToken = loginToken
  }
  res.headers.lang = lang // 当前选择的语言版本，用于后台国际化
  if (count > 0) {
    setTimeout(() => {
      loadingInstance.close() // 15S之后关闭遮罩
    }, 15000)
  }
  if (process.env.VUE_APP_ENTRY !== 'main') {
    // res.headers['Access-Control-Allow-Origin'] = '*'
  }
  return res
}, (error) => {
  count = 0
  loadingInstance.close()
  Promise.reject(error)
})
service.interceptors.response.use(
  (response) => {
    count--
    if (count <= 0) { // 所有请求都返回了，关掉loading
      count = 0
      loadingInstance.close()
    }
    const res = response.data
    const config = response.config
    if (res.success) {
      return response
    } else {
      if (config.url && ignoreName.indexOf(config.url) > -1) {
        // 忽略后端的message提示
      } else {
        if (res.message) {
          Message({
            message: res.message,
            type: 'error',
            duration: 5 * 1000
          })
        }
      }
      return response
    }
  },
  err => {
    count = 0
    loadingInstance.close()
    Message({
      message: err.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(err)
  }
)

export default (req: any) => {
  req.method === 'GET' ? delete req.data : delete req.params // get 参数用params， post 用data
  return service(req).then((res) => {
    return res.data
  })
}
